import React, { useState, useEffect, useCallback, useMemo } from 'react'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { patientCircleService, handleApiResponse, handleApiError } from '../../../utils/api'
import { useAppDispatch } from '../../../store'
import { postCollection, deleteCollection, publishComment, putExpressOpinion } from '../../../store/sliceReducer/PatientCircleSliceReducer'
import { Toast } from 'antd-mobile'
import TopNav from '../../../components/topNav'
import common_button_collection_large_n from '../../../assets/icon/common_button_collection_large_n.png'
import common_button_collection_large_s from '../../../assets/icon/common_button_collection_large_s.png'
import common_icon_comment_large_n from '../../../assets/icon/common_icon_comment_large_n.png'
import './index.css'

interface SickCircleInfo {
  sickCircleId: number
  authorUserId: number
  departmentId: number
  adoptFlag: number
  title: string
  department: string
  disease: string
  detail: string
  treatmentHospital: string
  treatmentStartTime: string
  treatmentEndTime: string
  treatmentProcess: string
  picture: string
  collectionFlag: number
  collectionNum: number
  commentNum: number
  adoptNickName: string
  adoptHeadPic: string
  adoptComment: string
  adoptTime: number
}

interface CommentItem {
  commentId: number
  commentUserId: number
  nickNmae: string
  headPic: string
  content: string
  supportNum: number
  opposeNum: number
  opinion: number
  whetherDoctor: number
  commentTime: number
}

const Index = () => {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const sickCircleId = searchParams.get('sickCircleId')
  
  // 从localStorage获取收藏状态
  const getStoredCollectionState = useCallback((sickCircleId: string) => {
    try {
      const stored = localStorage.getItem(`collection_${sickCircleId}`)
      return stored ? JSON.parse(stored) : null
    } catch (error) {
      console.error('解析收藏状态失败:', error)
      return null
    }
  }, [])

  // 保存收藏状态到localStorage
  const saveCollectionState = useCallback((sickCircleId: string, collectionFlag: number, collectionNum: number) => {
    try {
      const state = {
        collectionFlag,
        collectionNum,
        timestamp: Date.now()
      }
      localStorage.setItem(`collection_${sickCircleId}`, JSON.stringify(state))
    } catch (error) {
      console.error('保存收藏状态失败:', error)
    }
  }, [])

  const [sickCircleInfo, setSickCircleInfo] = useState<SickCircleInfo | null>(null)
  const [loading, setLoading] = useState(true)
  const [commentList, setCommentList] = useState<CommentItem[]>([
    {
      commentId: 1,
      commentUserId: 1001,
      nickNmae: "张医生",
      headPic: "",
      content: "这个症状建议及时就医检查，不要拖延。",
      commentTime: 1705287000000,
      supportNum: 15,
      opposeNum: 2,
      opinion: 0,
      whetherDoctor: 1
    },
    {
      commentId: 2,
      commentUserId: 1002,
      nickNmae: "病友小王",
      headPic: "",
      content: "我也有类似的经历，建议多休息，注意饮食。",
      commentTime: 1705282500000,
      supportNum: 8,
      opposeNum: 1,
      opinion: 0,
      whetherDoctor: 0
    },
    {
      commentId: 3,
      commentUserId: 1003,
      nickNmae: "李医生",
      headPic: "",
      content: "根据描述，建议做进一步检查确认病情。",
      commentTime: 1705279500000,
      supportNum: 12,
      opposeNum: 0,
      opinion: 0,
      whetherDoctor: 1
    },
    {
      commentId: 4,
      commentUserId: 1004,
      nickNmae: "病友小刘",
      headPic: "",
      content: "感谢分享，很有帮助的经验！",
      commentTime: 1705275600000,
      supportNum: 5,
      opposeNum: 0,
      opinion: 0,
      whetherDoctor: 0
    },
    {
      commentId: 5,
      commentUserId: 1005,
      nickNmae: "陈医生",
      headPic: "",
      content: "建议保持良好心态，积极配合治疗。",
      commentTime: 1705272600000,
      supportNum: 20,
      opposeNum: 1,
      opinion: 0,
      whetherDoctor: 1
    }
  ])
  const [commentLoading, setCommentLoading] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMoreComments, setHasMoreComments] = useState(true)
  const [collectionLoading, setCollectionLoading] = useState(false)
  const [commentOverlayVisible, setCommentOverlayVisible] = useState(false)
  const [newComment, setNewComment] = useState('')
  const [publishCommentLoading, setPublishCommentLoading] = useState(false)

  // 获取病友圈详情
  const fetchSickCircleInfo = useCallback(async () => {
    if (!sickCircleId) return
    
    try {
      const response = await patientCircleService.getSickCircleDetail({
        sickCircleId: Number(sickCircleId)
      })
      
      const result = handleApiResponse<SickCircleInfo>(response)
      
      // 优先使用本地存储的收藏状态
      const storedState = getStoredCollectionState(sickCircleId)
      if (storedState) {
        // 使用本地收藏状态，但保留其他接口数据
        setSickCircleInfo({
          ...result,
          collectionFlag: storedState.collectionFlag,
          collectionNum: storedState.collectionNum
        })
      } else {
        // 没有本地状态，使用接口数据并保存到本地
        setSickCircleInfo(result)
        saveCollectionState(sickCircleId, result.collectionFlag, result.collectionNum)
      }
    } catch (error) {
      console.error('获取病友圈详情失败:', handleApiError(error))
      setSickCircleInfo(null)
    } finally {
      setLoading(false)
    }
  }, [sickCircleId, getStoredCollectionState, saveCollectionState])

  // 获取评论列表
  const fetchCommentList = useCallback(async (page: number = 1, isLoadMore: boolean = false) => {
    if (!sickCircleId) return
    
    try {
      setCommentLoading(true)
      const response = await patientCircleService.getSickCircleCommentList({
        sickCircleId: Number(sickCircleId),
        page,
        count: 10
      })
      
      const result = handleApiResponse<CommentItem[]>(response)
      
      if (isLoadMore) {
        setCommentList(prev => [...prev, ...result])
      } else {
        setCommentList(result)
      }
      
      // 判断是否还有更多评论
      setHasMoreComments(result.length === 10)
      setCurrentPage(page)
    } catch (error) {
      console.error('获取评论列表失败:', handleApiError(error))
    } finally {
      setCommentLoading(false)
    }
  }, [sickCircleId])

  // 加载更多评论
  const loadMoreComments = () => {
    if (!commentLoading && hasMoreComments) {
      fetchCommentList(currentPage + 1, true)
    }
  }

  // 跳转到用户发帖列表页面
  const handleUserClick = (userId: number) => {
    navigate(`/BpatientCircle/PeopleCommentList?patientUserId=${userId}`)
  }

  // 处理收藏/取消收藏
  const handleCollectionClick = useCallback(async () => {
    if (!sickCircleInfo || collectionLoading || !sickCircleId) return

    try {
      setCollectionLoading(true)
      
      if (sickCircleInfo.collectionFlag === 1) {
        // 当前已收藏，执行取消收藏
        await dispatch(deleteCollection({ sickCircleId: sickCircleInfo.sickCircleId }))
        
        const newCollectionFlag = 0
        const newCollectionNum = Math.max(0, sickCircleInfo.collectionNum - 1)
        
        // 更新本地状态
        setSickCircleInfo(prev => prev ? {
          ...prev,
          collectionFlag: newCollectionFlag,
          collectionNum: newCollectionNum
        } : null)
        
        // 保存到本地存储
        saveCollectionState(sickCircleId, newCollectionFlag, newCollectionNum)
        
        Toast.show({
          content: '取消收藏成功',
          icon: 'success',
          duration: 1500,
        })
      } else {
        // 当前未收藏，执行收藏
        await dispatch(postCollection({ sickCircleId: sickCircleInfo.sickCircleId }))
        
        const newCollectionFlag = 1
        const newCollectionNum = sickCircleInfo.collectionNum + 1
        
        // 更新本地状态
        setSickCircleInfo(prev => prev ? {
          ...prev,
          collectionFlag: newCollectionFlag,
          collectionNum: newCollectionNum
        } : null)
        
        // 保存到本地存储
        saveCollectionState(sickCircleId, newCollectionFlag, newCollectionNum)
        
        Toast.show({
          content: '收藏成功',
          icon: 'success',
          duration: 1500,
        })
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
      Toast.show({
        content: '操作失败，请重试',
        icon: 'fail',
        duration: 2000,
      })
    } finally {
      setCollectionLoading(false)
    }
  }, [sickCircleInfo, collectionLoading, dispatch, sickCircleId, saveCollectionState])

  // 处理评论按钮点击
  const handleCommentClick = useCallback(() => {
    setCommentOverlayVisible(true)
  }, [])

  // 关闭评论遮罩层
  const handleCloseCommentOverlay = useCallback(() => {
    setCommentOverlayVisible(false)
  }, [])

  // 发表评论
  const handlePublishComment = useCallback(async () => {
    if (!newComment.trim() || !sickCircleInfo || publishCommentLoading) return

    try {
      setPublishCommentLoading(true)
      
      await dispatch(publishComment({
        sickCircleId: sickCircleInfo.sickCircleId,
        content: newComment.trim()
      }))
      
      // 清空输入框
      setNewComment('')
      
      // 隐藏遮罩层
      setCommentOverlayVisible(false)
      
      // 重新获取评论列表
      await fetchCommentList(1, false)
      
      // 更新评论数量
      setSickCircleInfo(prev => prev ? {
        ...prev,
        commentNum: prev.commentNum + 1
      } : null)
      
      Toast.show({
        content: '评论发表成功',
        icon: 'success',
        duration: 1500,
      })
    } catch (error) {
      console.error('发表评论失败:', error)
      Toast.show({
        content: '发表评论失败，请重试',
        icon: 'fail',
        duration: 2000,
      })
    } finally {
      setPublishCommentLoading(false)
    }
  }, [newComment, sickCircleInfo, publishCommentLoading, dispatch, fetchCommentList])

  // 处理点赞/反对
  const handleOpinionClick = useCallback(async (commentId: number, opinion: number) => {
    try {
      await dispatch(putExpressOpinion({ commentId, opinion }))
      
      // 重新获取评论列表以更新点赞数
      await fetchCommentList(currentPage, false)
      
      Toast.show({
        content: opinion === 1 ? '点赞成功' : '反对成功',
        icon: 'success',
        duration: 1000,
      })
    } catch (error) {
      console.error('操作失败:', error)
      Toast.show({
        content: '操作失败，请重试',
        icon: 'fail',
        duration: 2000,
      })
    }
  }, [dispatch, fetchCommentList, currentPage])

  // 计算属性：是否有被采纳的建议
  const hasAdoptedSuggestion = useMemo(() => {
    return sickCircleInfo?.adoptFlag === 1
  }, [sickCircleInfo?.adoptFlag])

  // 计算属性：是否可以加载更多评论
  const canLoadMoreComments = useMemo(() => {
    return !commentLoading && hasMoreComments
  }, [commentLoading, hasMoreComments])

  useEffect(() => {
    if (sickCircleId) {
      const loadData = async () => {
        await fetchSickCircleInfo()
        await fetchCommentList(1, false)
      }
      loadData()
    }
  }, [sickCircleId, fetchSickCircleInfo, fetchCommentList])

  if (loading) {
    return <div className="loading">加载中...</div>
  }

  if (!sickCircleInfo) {
    return <div className="error">数据加载失败</div>
  }

  return (
    <div className="sick-circle-detail">
      {/* 头部导航 */}
      <TopNav title="病友圈详情" />

      {/* 页面内容区域 */}
      <div className="sick-circle-content">
        {/* 基本信息 */}
      <div className="info-section">
        <div className="info-item">
          <span className="label">标题：</span>
          <span className="value">{sickCircleInfo.title || '暂无'}</span>
        </div>
        <div className="info-item">
          <span className="label">科室：</span>
          <span className="value">{sickCircleInfo.department || '暂无'}</span>
        </div>
        <div className="info-item">
          <span className="label">病症描述：</span>
          <span className="value">{sickCircleInfo.disease || '暂无'}</span>
        </div>
        <div className="info-item">
          <span className="label">病症详情：</span>
          <span className="value">{sickCircleInfo.detail || '暂无'}</span>
        </div>
      </div>

      {/* 治疗信息 */}
      <div className="info-section">
        <div className="info-item">
          <span className="label">治疗医院：</span>
          <span className="value">{sickCircleInfo.treatmentHospital || '暂无'}</span>
        </div>
        <div className="info-item">
          <span className="label">治疗开始时间：</span>
          <span className="value">{sickCircleInfo.treatmentStartTime || '暂无'}</span>
        </div>
        <div className="info-item">
          <span className="label">治疗结束时间：</span>
          <span className="value">{sickCircleInfo.treatmentEndTime || '暂无'}</span>
        </div>
        <div className="info-item">
          <span className="label">治疗过程描述：</span>
          <span className="value">{sickCircleInfo.treatmentProcess || '暂无'}</span>
        </div>
      </div>

      {/* 相关图片 */}
      <div className="info-section">
        <div className="info-item">
          <span className="label">相关图片：</span>
          <div className="value">
            {sickCircleInfo.picture ? (
              <img src={sickCircleInfo.picture} alt="相关图片" className="detail-image" />
            ) : (
              <span>暂无</span>
            )}
          </div>
        </div>
      </div>

      {/* 互动信息 */}
      <div className="info-section">
        <div className="info-item">
          <span className="label">是否收藏：</span>
          <span className="value">{sickCircleInfo.collectionFlag === 1 ? '是' : '否'}</span>
        </div>
        <div className="info-item">
          <span className="label">收藏数：</span>
          <span className="value">{sickCircleInfo.collectionNum || 0}</span>
        </div>
        <div className="info-item">
          <span className="label">评论数(建议数)：</span>
          <span className="value">{sickCircleInfo.commentNum || 0}</span>
        </div>
        <div className="info-item">
          <span className="label">是否有采纳建议：</span>
          <span className="value">{sickCircleInfo.adoptFlag === 1 ? '有' : '无'}</span>
        </div>
      </div>

      {/* 被采纳的建议 */}
      {hasAdoptedSuggestion && (
        <div className="info-section">
          <div className="info-item">
            <span className="label">采纳用户昵称：</span>
            <span 
              className="value clickable-user" 
              onClick={() => handleUserClick(sickCircleInfo.authorUserId)}
            >
              {sickCircleInfo.adoptNickName || '暂无'}
            </span>
          </div>
          <div className="info-item">
            <span className="label">采纳用户头像：</span>
            <div className="value">
              {sickCircleInfo.adoptHeadPic ? (
                <img 
                  src={sickCircleInfo.adoptHeadPic} 
                  alt="用户头像" 
                  className="user-avatar clickable-avatar"
                  onClick={() => handleUserClick(sickCircleInfo.authorUserId)}
                />
              ) : (
                <span>暂无</span>
              )}
            </div>
          </div>
          <div className="info-item">
            <span className="label">采纳建议：</span>
            <span className="value">{sickCircleInfo.adoptComment || '暂无'}</span>
          </div>
          <div className="info-item">
            <span className="label">采纳时间：</span>
            <span className="value">
              {sickCircleInfo.adoptTime ? new Date(sickCircleInfo.adoptTime).toLocaleString() : '暂无'}
            </span>
          </div>
        </div>
      )}

      {/* 互动区域 */}
      <div className="interaction-area">
        <div className="stats">
          <div 
            className={`stat-item ${collectionLoading ? 'loading' : ''}`}
            onClick={handleCollectionClick}
            style={{ cursor: collectionLoading ? 'not-allowed' : 'pointer' }}
          >
            <img 
              src={sickCircleInfo.collectionFlag === 1 ? common_button_collection_large_s : common_button_collection_large_n} 
              alt="收藏" 
              className="stat-icon"
            />
            <span className="stat-count">{sickCircleInfo.collectionNum}</span>
            {collectionLoading && <span className="loading-text">处理中...</span>}
          </div>
          <div 
            className="stat-item"
            onClick={handleCommentClick}
            style={{ cursor: 'pointer' }}
          >
            <img src={common_icon_comment_large_n} alt="评论" className="stat-icon" />
            <span className="stat-count">{sickCircleInfo.commentNum}</span>
          </div>
        </div>
      </div>

      {/* 评论列表 */}
      <div className="comment-section">
        <div className="comment-header">
          <h3>评论列表 ({commentList.length})</h3>
        </div>
        
        {commentLoading && commentList.length === 0 ? (
          <div className="comment-loading">加载评论中...</div>
        ) : (
          <div className="comment-list">
            {commentList.map((comment) => (
              <div key={comment.commentId} className="comment-item">
                <div className="comment-user">
                  <img 
                    src={comment.headPic || '/default-avatar.png'} 
                    alt="用户头像" 
                    className="comment-avatar clickable-avatar"
                    onClick={() => handleUserClick(comment.commentUserId)}
                  />
                  <div className="comment-user-info">
                    <div 
                      className="comment-nickname clickable-user"
                      onClick={() => handleUserClick(comment.commentUserId)}
                    >
                      {comment.nickNmae}
                      {comment.whetherDoctor === 1 && (
                        <span className="doctor-badge">医生</span>
                      )}
                    </div>
                    <div className="comment-time">
                      {new Date(comment.commentTime).toLocaleString()}
                    </div>
                  </div>
                </div>
                
                <div className="comment-content">
                  {comment.content}
                </div>
                
                <div className="comment-actions">
                  <div className="comment-stats">
                    <span className={`support-count ${comment.opinion === 1 ? 'active' : ''}`}>
                      赞同 {comment.supportNum}
                    </span>
                    <span className={`oppose-count ${comment.opinion === 2 ? 'active' : ''}`}>
                      反对 {comment.opposeNum}
                    </span>
                  </div>
                </div>
              </div>
            ))}
            
            {commentList.length === 0 && !commentLoading && (
              <div className="no-comments">暂无评论</div>
            )}
            
            {canLoadMoreComments && commentList.length > 0 && (
              <div className="load-more">
                <button 
                  className="load-more-btn" 
                  onClick={loadMoreComments}
                  disabled={commentLoading}
                >
                  {commentLoading ? '加载中...' : '加载更多评论'}
                </button>
              </div>
            )}
          </div>
        )}
      </div>
      </div>

      {/* 半透明深色遮罩层 */}
      {commentOverlayVisible && (
        <div className="comment-overlay">
          {/* 评论弹窗(白色矩形框) */}
          <div className="comment-popup">
            {/* 评论列表 */}
            <div className="popup-comment-list">
              {commentList.length > 0 ? (
                commentList.map((comment, index) => (
                  <div key={comment.commentId}>
                    <div className="popup-comment-item">
                      <div className="comment-avatar-section">
                        {comment.whetherDoctor === 1 ? (
                          <div className="doctor-avatar">
                            <div className="doctor-icon">+</div>
                          </div>
                        ) : (
                          <div className="user-avatar">
                            <div className="avatar-placeholder">
                              {comment.nickNmae ? comment.nickNmae.charAt(0) : '用'}
                            </div>
                          </div>
                        )}
                      </div>
                      <div className="comment-content-section">
                        <div className="comment-header">
                          <span className="comment-nickname">{comment.nickNmae || '匿名用户'}</span>
                          <span className="comment-date">
                            {new Date(comment.commentTime).toLocaleDateString()}
                          </span>
                        </div>
                        <div className="comment-text">
                          {comment.content}
                        </div>
                        <div className="comment-actions">
                          <div 
                            className="action-item"
                            onClick={() => handleOpinionClick(comment.commentId, 1)}
                            style={{ cursor: 'pointer' }}
                          >
                            <span className="action-icon">👍</span>
                            <span className="action-count">{comment.supportNum}</span>
                          </div>
                          <div 
                            className="action-item"
                            onClick={() => handleOpinionClick(comment.commentId, 2)}
                            style={{ cursor: 'pointer' }}
                          >
                            <span className="action-icon">👎</span>
                            <span className="action-count">{comment.opposeNum}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    {index < commentList.length - 1 && (
                      <div className="comment-divider"></div>
                    )}
                  </div>
                ))
              ) : (
                <div className="no-comments-popup">
                  <div className="no-comments-text">暂无评论</div>
                </div>
              )}
            </div>

            {/* 底部输入区域 */}
            <div className="popup-input-area">
              <button 
                className="close-button"
                onClick={handleCloseCommentOverlay}
              >
                ✕
              </button>
              <div className="input-container">
                <input
                  type="text"
                  value={newComment}
                  onChange={(e) => setNewComment(e.target.value)}
                  placeholder="在此留下高见吧!!"
                  className="comment-input"
                />
                <button 
                  className="send-button"
                  onClick={handlePublishComment}
                  disabled={!newComment.trim() || publishCommentLoading}
                >
                  ↑
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default Index